package com.wcl.demo.ui.adapter;

import android.widget.BaseAdapter;
import android.graphics.Bitmap;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.easemob.chat.EMMessage;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.wcl.demo.R;
import com.wcl.demo.model.entity.SearchHimUser;
import com.wcl.demo.network.VolleySingleton;
import com.wcl.demo.utils.DialogUtils;
import com.wcl.demo.utils.PreferenceManager;
import com.wcl.demo.utils.ProgressUtils;
import com.wcl.demo.view.CircleImage;
import com.wcl.demo.utils.FaceConversionUtil;
import com.wcl.demo.utils.TimeStampUtils;

import java.io.IOException;
import java.util.List;


/**
 * Created by dllo on 15/11/23.
 */
public class ChatAdapter extends BaseAdapter {
    private List<EMMessage> datas;//定义消息
    private MediaPlayer player;//定义媒体播放器
    private Context context;//定义Context
    private SearchHimUser user;
    private VolleySingleton volleySingleton = VolleySingleton.getInstance();//定义Volley请求
    private String headimageurl;


    public ChatAdapter(Context context) {
        this.context = context;
    }

    public void addData(List<EMMessage> datas , String headimageurl) {
        this.headimageurl = headimageurl;
        this.datas = datas;
        Log.i("kkkkkccc", datas + "");
        Log.i("headimageurl" , headimageurl + "");
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return datas != null && datas.size() > 0 ? datas.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chatlist_right_item, null);
            //左边TextView显示文字
            holder.chat_left = (TextView) convertView.findViewById(R.id.chat_left);
            //右边边TextView显示文字
            holder.chat_right = (TextView) convertView.findViewById(R.id.chat_right);
            //左边ImageView显示发送的图片
            holder.chat_right_image = (ImageView) convertView.findViewById(R.id.chat_right_image);
            //右边ImageView显示发送的图片
            holder.chat_left_image = (ImageView) convertView.findViewById(R.id.chat_left_image);
            //左边的头像
            holder.left_headImage = (CircleImage) convertView.findViewById(R.id.left_headImage);
            //右边头像
            holder.right_headImage = (CircleImage) convertView.findViewById(R.id.right_headImage);
            //显示聊天时间
            holder.chat_time = (TextView) convertView.findViewById(R.id.chat_time);
            //聊天左边布局
            holder.chat_left_layout = (FrameLayout) convertView.findViewById(R.id.chat_left_layout);
            //聊天右边布局
            holder.chat_right_layout = (FrameLayout) convertView.findViewById(R.id.chat_right_layout);
            //左边显示位置的TextView
            holder.location_left_Text = (TextView) convertView.findViewById(R.id.location_left_Text);
            //左边显示位置的背景
            holder.location_background_leftIv = (ImageView) convertView.findViewById(R.id.location_background_leftIv);
            //右边显示位置的TextView
            holder.location_right_Text = (TextView) convertView.findViewById(R.id.location_right_Text);
            //右边显示未知的背景
            holder.location_background_rightIv = (ImageView) convertView.findViewById(R.id.location_background_rightIv);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        /****将接收来的消息设置在聊天界面***/
        EMMessage emMessage = datas.get(position);
        final String fromName = emMessage.getFrom();
        String toName = emMessage.getTo();
        final String name = emMessage.getUserName();
        Log.i("lanougg", name);
        //刚进入界面的时候将所有控件隐藏
        holder.chat_left.setVisibility(View.GONE);
        holder.chat_right.setVisibility(View.GONE);
        holder.chat_right_image.setVisibility(View.GONE);
        holder.chat_left_image.setVisibility(View.GONE);
        holder.left_headImage.setVisibility(View.GONE);
        holder.right_headImage.setVisibility(View.GONE);
        holder.location_right_Text.setVisibility(View.GONE);
        holder.location_background_rightIv.setVisibility(View.GONE);
        //设置发送时间
        long time = emMessage.getMsgTime() / 1000 - TimeStampUtils.getTimesmorning();
        Log.i("lanou", "------------>" + time + "   " + TimeStampUtils.getTimesmorning());
        if ((time > 0 || time == 0) && time < 86400) {
            holder.chat_time.setText("今天" + TimeStampUtils.stampToDate2(emMessage.getMsgTime()));
        } else if (time < 0 && ((time + 86400) > 0 || (time + 86400) == 0)) {
            holder.chat_time.setText("昨天" + TimeStampUtils.stampToDate2(emMessage.getMsgTime()));
        } else {
            holder.chat_time.setText(TimeStampUtils.stampToDate(emMessage.getMsgTime()));
        }

        switch (emMessage.getType()) {
            case TXT:         //发送文字
                TextMessageBody body = (TextMessageBody) emMessage.getBody();
                String text = body.getMessage();
                if (name.equals(fromName)) {//如果名字是对方的名字
                    holder.chat_left.setVisibility(View.VISIBLE);
                    holder.left_headImage.setVisibility(View.VISIBLE);
                    getBitmap(headimageurl, holder.left_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, text);
                    holder.chat_left.setText(spannableString);
                } else {//否则显示右边气泡并将内容设置在气泡上
                    holder.chat_right.setVisibility(View.VISIBLE);
                    holder.right_headImage.setVisibility(View.VISIBLE);
                    getBitmap(getCurrentUserAvatar(), holder.right_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, text);
                    holder.chat_right.setText(spannableString);
                    holder.chat_left.setText(text);
                }
                break;
            case IMAGE:          //发送图片
                ImageMessageBody imageMessageBody = (ImageMessageBody) emMessage.getBody();//创建消息体
                String bitmap = imageMessageBody.getRemoteUrl();//从消息体上得到内容
                if (name.equals(fromName)) {//如果名字是对方的名字
                    holder.left_headImage.setVisibility(View.VISIBLE);
                    holder.chat_left_image.setVisibility(View.VISIBLE);//显示左边气泡
                    getBitmap(user.getAvatar(), holder.left_headImage);
                    getBitmap(bitmap, holder.chat_left_image);
                } else {//否则显示右边气泡并将内容设置在气泡上
                    holder.right_headImage.setVisibility(View.VISIBLE);
                    holder.chat_right_image.setVisibility(View.VISIBLE);
                    getBitmap(getCurrentUserAvatar(), holder.right_headImage);
                    getBitmap(imageMessageBody.getLocalUrl(), holder.chat_right_image);
                }
                break;
            case VOICE:        //声音
                final VoiceMessageBody bodyVoice = (VoiceMessageBody) emMessage.getBody();//定义消息体为声音的消息体
                final String voice = bodyVoice.getRemoteUrl(); //从消息得到声音
                if (voice != null) {
                    Log.i("hhhhhh", voice);
                }
                final ViewHolder finalHolder = holder;
                if (name.equals(fromName)) {    //如果名字是对方的名字(聊天气泡在左边)
                    holder.chat_left_image.setVisibility(View.VISIBLE); //显示左边的聊天气泡
                    holder.left_headImage.setVisibility(View.VISIBLE);
                    getBitmap(headimageurl, holder.left_headImage);
                    holder.chat_left_image.setImageResource(R.mipmap.iconfont_yuyin_chat_left);  //将声音设置在左边气泡上
                    holder.chat_left_image.setOnClickListener(new View.OnClickListener() {//点击气泡播放声音
                        @Override
                        public void onClick(View v) {
                            playMedia(voice, finalHolder.chat_left_image, name, fromName);  //播放录音
                        }
                    });
                } else {   //否则则显示右边聊天气泡并将声音设置在右边聊天气泡上
                    holder.chat_right_image.setVisibility(View.VISIBLE);
                    holder.right_headImage.setVisibility(View.VISIBLE);
                    getBitmap(getCurrentUserAvatar(), holder.right_headImage);
                    holder.chat_right_image.setImageResource(R.mipmap.iconfont_yuyin_chat_right);
                    holder.chat_right_image.setOnClickListener(new View.OnClickListener() {//点击气泡播放语音
                        @Override
                        public void onClick(View v) {
                            playMedia(voice, finalHolder.chat_right_image, name, fromName);//播放录音
                        }
                    });
                }
                break;
            case FILE:      //发送文件
                FileMessageBody messageBody = (FileMessageBody) emMessage.getBody();
                String file = messageBody.getRemoteUrl();
                if (name.equals(fromName)) { //如果名字是对方的名字(聊天气泡在左边)
                    holder.chat_left.setVisibility(View.VISIBLE);
                    holder.left_headImage.setVisibility(View.VISIBLE);
                    getBitmap(headimageurl, holder.left_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, file);
                    holder.chat_left.setText(file);
                } else { //否则则显示右边聊天气泡并将声音设置在右边聊天气泡上
                    holder.chat_right.setVisibility(View.VISIBLE);
                    holder.right_headImage.setVisibility(View.VISIBLE);
                    getBitmap(getCurrentUserAvatar(), holder.right_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, file);
                    holder.chat_right.setText(spannableString);
                    holder.chat_left.setText(file);
                }
                break;
            case LOCATION: //发送位置
                LocationMessageBody locationMessageBody = (LocationMessageBody) emMessage.getBody();
                String adr = locationMessageBody.getAddress();
                if (name.equals(fromName)) { //如果名字是对方的名字(聊天气泡在左边)
                    holder.location_background_leftIv.setVisibility(View.VISIBLE);
                    holder.location_left_Text.setVisibility(View.VISIBLE);
                    holder.left_headImage.setVisibility(View.VISIBLE);
                    getBitmap(headimageurl, holder.left_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, adr);
                    holder.location_left_Text.setText(adr);
                } else { //否则则显示右边聊天气泡并将声音设置在右边聊天气泡上
                    holder.location_background_rightIv.setVisibility(View.VISIBLE);
                    holder.location_right_Text.setVisibility(View.VISIBLE);
                    holder.right_headImage.setVisibility(View.VISIBLE);
                    getBitmap(getCurrentUserAvatar(), holder.right_headImage);
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, adr);
                    holder.location_right_Text.setText(spannableString);
                    holder.location_right_Text.setText(adr);
                }
                break;
        }

        /*****************  行布局点击监听  *****************/
        holder.chat_left_layout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //删除当前会话的某条聊天记录
                DialogUtils.deleteSigleChat(parent.getContext(), datas.get(position).getFrom(), datas.get(position).getMsgId(), ChatAdapter.this);
                return false;
            }
        });
        holder.chat_right_layout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                //删除当前会话的某条聊天记录
                DialogUtils.deleteSigleChat(parent.getContext(), datas.get(position).getUserName(), datas.get(position).getMsgId(), ChatAdapter.this);

                addData(datas , headimageurl);
                notifyDataSetChanged();
                ProgressUtils.dismissProgress();
                return false;
            }
        });
        return convertView;
    }

    /****
     * 定义控件
     */
    public class ViewHolder {
        private TextView chat_right, chat_left, chat_time, location_right_Text, location_left_Text;
        private ImageView chat_right_image, chat_left_image, location_background_rightIv, location_background_leftIv;
        private CircleImage left_headImage, right_headImage;
        private FrameLayout chat_left_layout, chat_right_layout;
    }

    /***
     * 播放录音
     */
    private void playMedia(String body, final ImageView imageView, final String name, final String fromName) {
        try {
            player = new MediaPlayer();
            player.reset();
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(body);
            //Log.i("jdjgjkklf", body.getLocalUrl());
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    player.start();
                    if (name.equals(fromName)) {
                        imageView.setImageResource(R.mipmap.iconfont_yuyin_chat_left_press);
                    } else {
                        imageView.setImageResource(R.mipmap.iconfont_yuyinshuru_chat_right_press);
                        Log.i("lanou3g", "开始播放");
                    }
                }
            });
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (name.equals(fromName)) {
                        imageView.setImageResource(R.mipmap.iconfont_yuyin_chat_left);
                    }
                    imageView.setImageResource(R.mipmap.iconfont_yuyin_chat_right);
                    player.release();
                    player = null;
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    if (player.isPlaying()) {
                        player.stop();
                        if (name.equals(fromName)) {
                            imageView.setImageResource(R.mipmap.iconfont_yuyin_chat_left);
                        }
                        imageView.setImageResource(R.mipmap.iconfont_yuyin_chat_right);
                        Log.i("lanou3g", "停止播放");
                    }
                    player.release();
                    player = null;
                    return false;
                }
            });
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    /***
     * 图片请求
     *
     * @param bitmap
     * @param imageView
     */
    private void getBitmap(String bitmap, final ImageView imageView) {
        volleySingleton.getImageResuest(bitmap, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        });
    }

    private String getCurrentUserNick() {
        return PreferenceManager.getInstance().getCurrentUserNick();
    }

    private String getCurrentUserAvatar() {
        return PreferenceManager.getInstance().getCurrentUserAvatar();
    }
}